
package dao;

import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * EJB de DAO : Echange direct avec la base de données
 * @author Alex
 */
@Stateless
public class ObjectDAO implements ObjectDAOI{

    @PersistenceContext(unitName="Miagetest-PU")
    private EntityManager em;
    
    @Override
    public void insert(Object object, Object id) throws EntityAlreadyExistsException
    {
        Object objectTest = em.find(object.getClass(), id);

        if(objectTest != null)
            throw new EntityAlreadyExistsException(object, id);

        em.persist(object);
    }

    @Override
    public Object get(Class objectType, Object id) throws InexistantEntityException
    {
        Object objectTest = em.find(objectType, id);

        if(objectTest == null)
            throw new InexistantEntityException(objectType, id);

        return objectTest;
    }

    @Override
    public List<?> getAll(Class objectType)
    {
        Query query = em.createQuery("select object(o) from " + objectType.getSimpleName() + " as o");
        //query.setParameter("objectType", objectType.getSimpleName());
        return query.getResultList();
    }

    @Override
    public List<?> getObjectsQuery(String stringQuery, Map<String, Object> parameterList)
    {
        Query query = em.createQuery(stringQuery);

        for(String parameterName : parameterList.keySet())
            query.setParameter(parameterName, parameterList.get(parameterName));

        return query.getResultList();
    }

    @Override
    public void update(Object object)
    {
        em.merge(object);
    }

    @Override
    public void delete(Object object)
    {
        em.remove(object);
    }


}
